{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Copyright 2019 Google Inc. All Rights Reserved.\n",
    "#\n",
    "# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "# you may not use this file except in compliance with the License.\n",
    "# You may obtain a copy of the License at\n",
    "#\n",
    "#     http://www.apache.org/licenses/LICENSE-2.0\n",
    "#\n",
    "# Unless required by applicable law or agreed to in writing, software\n",
    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "# See the License for the specific language governing permissions and\n",
    "# limitations under the License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simple notebook pipeline \n",
    "\n",
    "Welcome to your first steps with Kubeflow Pipelines (KFP). This notebook demos: \n",
    "\n",
    "* Defining a Kubeflow pipeline with the KFP SDK\n",
    "* Creating an experiment and submitting pipelines to the KFP run time environment using the KFP SDK \n",
    "\n",
    "Reference documentation: \n",
    "* https://www.kubeflow.org/docs/pipelines/sdk/sdk-overview/\n",
    "* https://www.kubeflow.org/docs/pipelines/sdk/build-component/"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Prerequisites: Install the pipelines SDK\n",
    "If you followed the [notebook setup instructions](https://www.kubeflow.org/docs/notebooks/setup/) then you don't have to run the next cell.  You only need to install the KFP package once in your notebook server.  You can find the latest KFP package [here](https://github.com/kubeflow/pipelines/releases)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# If you've already done this during setup you don't need to do it again\n",
    "!pip3 install kfp --upgrade"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setup\n",
    "<b> Important: </b> Make sure to use your GCP project name and a GCS bucket for saving the pipelines.  If you haven't already, [setup a GCS bucket](https://cloud.google.com/storage/docs/creating-buckets)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "parameters"
    ]
   },
   "outputs": [],
   "source": [
    "# Set your output directory and project name. \n",
    "PROJECT_NAME =  '[YOUR-GCP-PROJECT-NAME]'           # 'Your-Gcp-Project-Name'\n",
    "OUTPUT_DIR = 'gs://[YOUR-GCS-BUCKET]/assets'        # A path for asset outputs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "EXPERIMENT_NAME = 'Simple notebook pipeline'                    # Name of the experiment in the UI\n",
    "BASE_IMAGE = 'tensorflow/tensorflow:2.0.0b0-py3'    # Base image used for components in the pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import kfp\n",
    "import kfp.dsl as dsl\n",
    "from kfp import compiler"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Create pipeline component"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Create python function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@dsl.python_component(\n",
    "    name='add_op',\n",
    "    description='adds two numbers',\n",
    "    base_image=BASE_IMAGE  # you can define the base image here, or when you build in the next step. \n",
    ")\n",
    "def add(a: float, b: float) -> float:\n",
    "    '''Calculates sum of two arguments'''\n",
    "    print(a, '+', b, '=', a + b)\n",
    "    return a + b"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Build pipeline component from the function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "# Docker image for the pipeline component\n",
    "TARGET_IMAGE = 'gcr.io/%s/add-op:latest' % PROJECT_NAME \n",
    "\n",
    "# The return value \"DeployerOp\" represents a step that is used in a pipeline\n",
    "add_op = compiler.build_python_component(\n",
    "    component_func=add,\n",
    "    staging_gcs_path=OUTPUT_DIR,\n",
    "    base_image=BASE_IMAGE,\n",
    "    target_image=TARGET_IMAGE)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Build a pipeline using the component"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "@dsl.pipeline(\n",
    "   name='Calculation pipeline',\n",
    "   description='A toy pipeline that performs arithmetic calculations.'\n",
    ")\n",
    "def calc_pipeline(\n",
    "   a='0',\n",
    "   b='7',\n",
    "   c='17',\n",
    "):\n",
    "    #Passing pipeline parameter and a constant value as operation arguments\n",
    "    add_task = add_op(a, 4) #Returns a dsl.ContainerOp class instance. \n",
    "    \n",
    "    #You can create explicit dependency between the tasks using xyz_task.after(abc_task)\n",
    "    add_2_task = add_op(a, b)\n",
    "    \n",
    "    add_3_task = add_op(add_task.output, add_2_task.output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compile and run the pipeline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pipeline_func = calc_pipeline\n",
    "pipeline_filename = pipeline_func.__name__ + '.pipeline.zip'\n",
    "compiler.Compiler().compile(pipeline_func, pipeline_filename)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Create an Experiment in the Pipeline System\n",
    "\n",
    "Pipeline system requires an \"Experiment\" to group pipeline runs. You can create a new experiment, or call client.list_experiments() to get existing ones."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Get or create an experiment and submit a pipeline run\n",
    "client = kfp.Client()\n",
    "experiment = client.create_experiment(EXPERIMENT_NAME)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Submit the pipeline for execution"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#Specify pipeline argument values\n",
    "arguments = {'a': '7', 'b': '8'}\n",
    "\n",
    "#Submit a pipeline run\n",
    "run_name = pipeline_func.__name__ + ' run'\n",
    "run_result = client.run_pipeline(experiment.id, run_name, pipeline_filename, arguments)\n",
    "\n",
    "#This link leads to the run information page. \n",
    "#Note: There is a bug in JupyterLab that modifies the URL and makes the link stop working"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### That's it!\n",
    "You just created and deployed your first pipeline in Kubeflow!  You can put more complex python code within the functions, and you can import any libraries that are included in the base image (you can use [VersionedDependencies](https://kubeflow-pipelines.readthedocs.io/en/latest/source/kfp.compiler.html#kfp.compiler.VersionedDependency) to import libraries not included in the base image). "
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
